import { history as router } from 'umi';
import { Tabs, Dropdown, Menu } from 'antd';
import { DEFAULT_ROUTE } from '../shared.data';
import { useKeepAliveTabs } from '../hooks/useKeepAliveTabs';
import styles from './index.less';

const { TabPane } = Tabs;
const Nav = () => {
  const {
    keepAliveTabs,
    activeTabRoutePath,
    currPath,
    closeTab,
    menuItems,
    setActiveTabRoutePath,
    menuClick,
  } = useKeepAliveTabs();

  // 切换tabs
  const handleTabChange = path => {
    setActiveTabRoutePath(path);
    if (currPath !== path) {
      router.push(path);
    }
  };

  // 编辑项
  const onEdit = (targetPath, action) => {
    if (action === 'remove') {
      closeTab(targetPath);
    }
  };

  // 渲染tab标题的鼠标菜单
  const renderTitle = item => {
    const { title, cacheKey } = item;
    const menu = (
      <Menu onClick={menuClick}>
        {menuItems.map(item => {
          if (item.key === 'close' && cacheKey === DEFAULT_ROUTE.path) return null;
          return (
            <Menu.Item key={JSON.stringify({ cacheKey, type: item.key })}>{item.label}</Menu.Item>
          );
        })}
      </Menu>
    );
    return (
      <Dropdown overlay={menu} trigger={['contextMenu']}>
        <span>{title}</span>
      </Dropdown>
    );
  };

  return (
    <div className={styles['nav-wrap']}>
      <Tabs
        onTabClick={handleTabChange}
        activeKey={activeTabRoutePath}
        type="editable-card"
        onEdit={onEdit}
        hideAdd
      >
        <TabPane tab={renderTitle(DEFAULT_ROUTE)} key={DEFAULT_ROUTE.path} />
        {keepAliveTabs
          .filter(item => item.name !== DEFAULT_ROUTE.path)
          .map(item => (
            <TabPane tab={renderTitle(item)} key={item.id} />
          ))}
      </Tabs>
    </div>
  );
};

export default Nav;
